package net.minhdiep.androiddialoglistener;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import net.minhdiep.androiddialoglistener.util.DownloadXml;
import net.minhdiep.androiddialoglistener.util.XmlParser;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;

import java.util.Iterator;


/*
 * User: Minh Diep
 * Date: 5/18/13
 * Time: 9:58 PM
 */

public class ListenerActivity extends Activity implements DownloadXml.OnTaskListener{

    private TextView downloadXmlTv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sub);
        Button downloadXmlBtn = (Button) findViewById(R.id.download_xml_btn);
        downloadXmlTv = (TextView) findViewById(R.id.download_xml_tv);
        downloadXmlBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                downloadXmlTv.setText("Loading...");
                new DownloadXml(ListenerActivity.this).execute("http://news.google.com/?output=rss");
            }

        });
    }

    @Override
    public void downloadFinish(String result) {
        XmlParser xmlParser = new XmlParser();
        Document document = null;
        try {
            document = xmlParser.parse(result);
        } catch (DocumentException e) {
            e.printStackTrace();
        }

        assert document != null;
        Element channel = document.getRootElement().element("channel");
        String fun = "";
        for ( Iterator i = channel.elementIterator("item"); i.hasNext(); ) {
            Element item = (Element) i.next();
            fun += item.element("title").getText() + "\n\n";
        }
        downloadXmlTv.setText(fun);
    }
}